package 课上练习0419_scala_collection

import scala.collection.mutable

object Scala_04Map {
  def main(args: Array[String]): Unit = {
    println("===============创建Map====================")
    // 不可变
    val m1 = Map("hadoop" -> 1, "spark" -> 2, "flink" -> 3, "apache" -> 4) //class scala.collection.immutable.Map$Map4 --HashMap
    val m2 = Map(("hadoop", 1), ("spark", 2), ("flink", 3))
    // 可变
    val m3 = scala.collection.mutable.Map("hadoop" -> 1, "spark" -> 2, "flink" -> 3) // class scala.collection.mutable.HashMap
    val m4 = mutable.TreeMap(("hadoop", 1), ("spark", 2), ("flink", 3))
    println(m4)
    println("m1 Class: " + m1.getClass)
    println("m3 Class: " + m3.getClass)
    println("m4 Class: " + m4.getClass)
    println("===============遍历Map====================")
    // 取值
    println(m1("hadoop"))
    println(m1.getOrElse("hadoop", -1))
    println("===============遍历Map====================")
    for (key <- m1.keySet) {
      println(s"key: $key, value: ${m1(key)}")
    } // 通过keySet
    m1.keys.foreach(key => println(s"key: $key, value: ${m1(key)}")) // 通过keys
    m1.values.foreach(value => println(s"value: $value")) // 通过values
    // 直接遍历
    for (entry <- m1) {
      println(s"key: ${entry._1}, value: ${entry._2}")
    }
    for ((key, value) <- m1) {
      println(s"key: $key, value: $value")
    }
    println("===============修改Map====================")
    // 可变map修改，不可变map无法修改
    m3("hadoop") = 1
    m3.update("hadoop", 3)
    println(m3)
  }
}
